<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box" v-loading='loading'>
            <div class="form-title">新增学生</div>
            <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="80px" class="form" label-position='right'>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">学校班级信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="所属学校" prop="schoolName" :rules="rules.schoolName">
                                    <el-autocomplete v-model="dataForm.schoolName" :fetch-suggestions="remoteMethod" :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllGrade" style="width:95%"></el-autocomplete>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="this.schoolType == '0'">
                                <el-form-item label="年级" prop="grade" :rules="rules.schoolName">
                                    <el-select v-model="dataForm.grade" clearable placeholder="请选择" style="width:95%;" @change="queryAllClass( dataForm.grade )">
                                        <el-option v-for="item in gradeList" :key="item.pId" :label="item.sName" :value="item.pId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="班级名称" prop="classId" :rules="rules.schoolName">
                                    <el-select v-model="dataForm.classId" clearable placeholder="请选择" style="width:95%;">
                                        <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">基本信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="学生姓名" prop="studentName" :rules="rules.studentName">
                                    <el-popover
                                        placement="top-start"
                                        trigger="focus" 
                                        content="长度在12个字符以内。">
                                        <el-input v-model="dataForm.studentName" slot="reference" :maxlength="12" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="学籍号" prop="studentCode" :rules="rules.studentCode">
                                    <el-popover
                                        placement="top-start"
                                        trigger="focus" 
                                        content="长度在20个字符以内。">
                                        <el-input v-model="dataForm.studentCode" style="width:95%;" slot="reference" :maxlength="20"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="生日" prop="birthday" :rules="rules.birthday">
                                    <el-date-picker v-model="dataForm.birthday" :editable='false' style="width:95%;" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
                            </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="性别" prop="sex" :rules="rules.sex">
                                    <el-radio-group v-model="dataForm.sex">
                                        <el-radio label="0">男</el-radio>
                                        <el-radio label="1">女</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">家长信息</span>
                    </div>
                    <div class="form-content item">
                        <el-row :gutter="21" v-for="(item, index) in dataForm.contactWayList" :key="index">
                            <el-col :span="12">
                                <el-form-item :label="'联系人 ' + (index + 1)" :prop="'contactWayList.' + index + '.phone'"  :rules="index==0?rules.contactWay:rules.otherContactWay">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在11个字符以内。">
                                        <el-input v-model="item.phone" slot="reference" :maxlength="11" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" v-if="index != 0">
                                <el-button type="text" class="delBtn" @click="removeContactWay(index)"><i class="el-icon-delete"></i></el-button>
                            </el-col>
                        </el-row>
                        <el-button v-if="dataForm.contactWayList.length < 5" type="text" @click="addContactWay" class="addBtn btn-success"><i class="el-icon-plus"></i> 继续添加</el-button>
                    </div>
                </div>
                <div class="form-item">
                    <el-row>
                        <el-col :span="24">
                            <div class="footer">
                                <el-button @click="resetForm('dataForm')">取消</el-button>
                                <el-button type="primary" @click="submitForm('dataForm')">确认</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import { isEmpty } from 'utils/validate';
import moment from 'moment';
import Levelbar from "../../layout/Levelbar";
import { querySchoolByName } from 'api/common';
import {addStudent,getGrade,getClass} from "api/studentMange";
import { mapGetters } from "vuex";
import validate from '@/utils/validate';

export default {
    name: 'addStudentPage',
  components: { Levelbar },
  data() {
    const validateEmpty = (rule, value, callback) => {
        if (!isEmpty(value)) {
            callback(new Error('内容中不能存在空格'));
        } else {
            callback();
        }
    };
    
    return {
      loading: false,
      schoolType: '0',
      dataForm: {
        // 学校班级信息
        schoolName: "",
        schoolId: '',
        grade: "",
        classId: "",

        // 基本信息：
        studentName: "",
        studentCode: "",
        birthday: "",
        sex: "",

        // 家长信息
        contactWay: [],
        contactWayList: [{
            phone: ''
          }]
      },
      schoolLoading: false,
      schoolList: [],
      gradeList: [],
      classList: [],
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      },
      rules: {
        // 学校班级信息
        schoolName: [
          { required: true, message: "内容不能为空", trigger: "blur" }
          // { min: 1, max: 10, message: '长度在10个字符以内', trigger: 'blur' }
        ],

        // 基本信息：
        studentName: [
          { required: true, message: "请输入学生姓名", trigger: "blur" },
          { required: true, trigger: 'blur', validator: validateEmpty },
          { min: 1, max: 12, message: "长度在12个字符以内", trigger: "blur" }
        ],
        sex: [
          // { required: true, message: '请选择性别', trigger: 'blur' },
        ],
        studentCode: [
          { pattern: /^[A-Za-z0-9]+$/, message: '只允许输入数字和字母'},
          { min: 1, max: 20, message: "长度在20个字符以内", trigger: "blur" }
        ],
        birthday: [
          // { type: "date", required: true, message: "请选择日期", trigger: "change" }
        ],

        // 家长信息
        contactWay: [
            ...validate.phoneRequired()
        ],
        otherContactWay: [
            ...validate.phone()
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["uid"])
  },
  methods: {
    addContactWay() {
        this.dataForm.contactWayList.push({
          phone: ''
        });
    },
    removeContactWay(index) {
        if (index !== -1) {
          this.dataForm.contactWayList.splice(index, 1);
        }
    },
    submitForm(dataForm) {
        let phoneArray = [];
        this.dataForm.contactWayList.forEach(item => {
            if(item.phone) {
                phoneArray.push(item.phone);
            }
        });
        const items = new Set(phoneArray);
        if(items.size != phoneArray.length) {
            this.$message.error('联系人号码重复');
            return;
        }
      this.$refs[dataForm].validate(valid => {
        if (valid) {
          let phones = [];
          this.dataForm.contactWay = this.dataForm.contactWayList[0].phone;
          if(this.dataForm.contactWayList.length >1) {
              this.dataForm.contactWayList.forEach(function(item, index) {
                  if(index != 0 && item.phone) {
                      phones.push(item.phone);
                  }
              });
          }
          
          let userId = this.uid; // 创建人ID
          let schoolId = this.dataForm.schoolId;
          let schoolName = this.dataForm.schoolName;
          let gradeId = this.dataForm.grade; //  年级
          let classId = this.dataForm.classId; // 班级编号
          let studentName = this.dataForm.studentName; // 学生姓名
          let studentSex = this.dataForm.sex; //  性别
          let schoolrollCode = this.dataForm.studentCode; // 学籍号
          let birthDay = this.dataForm.birthday==''?'':moment(this.dataForm.birthday).format('YYYY-MM-DD'); // 生日
          let parentPhone = this.dataForm.contactWay; // 家长号码
          this.loading = true;
          addStudent(
            userId,
            schoolId,
            schoolName,
            gradeId,
            classId,
            studentName,
            studentSex,
            schoolrollCode,
            birthDay,
            parentPhone,
            phones
          ).then(response => {
            this.loading = false;
            if (response.data.status == 200) {
              this.$message.success(response.data.errorMsg);
              this.$refs[dataForm].resetFields();
              this.$router.push({ path: "/studentManage" });
              this.$store.dispatch('UpdateCache'); 
            } else {
              this.$message.error(response.data.errorMsg);
            }
          }).catch(() =>{
              this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    resetForm(dataForm) {
      this.$refs[dataForm].resetFields();
      this.$router.push({ path: "/studentManage" });
    },

    // 模糊查询学校名称
    remoteMethod(query, cb) {
        query = query.trim();
        if(query==''){
            cb([{value:'无数据'}]);
            this.$nextTick(()=>{
                let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                firstSelect.addClass('remoteMethodScy');
            })
        }
        if (query) {
          querySchoolByName(query).then(response => {
              this.schoolList = response.data.content;
          }).then(() => {
                let results = this.schoolList.filter(this.createStateFilter(query));
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    if(results.length){
                        let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                        firstSelect.removeClass('remoteMethodScy');
                        cb(results)
                    }else{
                        cb([{value:'无数据'}]);
                        this.$nextTick(()=>{
                            let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                            firstSelect.addClass('remoteMethodScy')
                        })
                    }
               }, 200 * Math.random());
          });
      } else {
            this.schoolType = '0';
            this.dataForm.grade = '';
            this.gradeList = [];
            this.dataForm.classId = '';
            this.classList = [];
            cb([{value:'无数据'}]);
            this.$nextTick(()=>{
                let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                firstSelect.addClass('remoteMethodScy')
            })
      }  
    },
    createStateFilter(query) {
        return (state) => {
            state.value = state.schoolName; 
            return (state.value.toLowerCase().includes(query.toLowerCase()));
        };
    },
   
    // 年级列表
    queryAllGrade(val) {
        this.dataForm.grade = '';
        this.gradeList = [];
        this.schoolType = val.schoolType;
        
        if(val.schoolId) {
            this.dataForm.schoolId = val.schoolId;
           
            if (this.schoolType == '1') {
                let schoolId = this.dataForm.schoolId;
                getClass(null, schoolId).then(response => {
                    this.classList = response.data.content;
                });
            } else {
                getGrade(val.schoolId).then(response => {
                    this.gradeList = response.data.content;
                });
            }  
        } else {
            this.dataForm.schoolName = '';
            this.schoolType = '0';
        }
    },

    // 班级列表
    queryAllClass(gradeId) {
        this.dataForm.classId = '';
        this.classList = [];

        if(this.dataForm.grade) {
            let schoolId = this.dataForm.schoolId;
            getClass(gradeId, schoolId).then(response => {
                this.classList = response.data.content;
            });
        }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
    .delBtn {
        font-size: 20px;
        color:#999;
    }
    .addBtn{
        margin-left:80px;
        font-size:14px;
        color:#ff5e2c;
    }
  .form-box {
    padding: 0 50px;
    @include showTitle();
    .form-title {
      padding-top:8px;
      text-align: center;
      font-size: 18px;
      color: #333;
      line-height: 72px;
      font-weight: bold;
      font-family: Microsoft YaHei;
      border-bottom: 1px solid #ddd;
    }
    .form {
      .form-item {
        padding-bottom: 40px;
        .form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
           
          .note-css {
            vertical-align: middle;
            display: inline-block;
            width: 4px;
            height: 14px;
            margin-right: 26px;
            border-left: 3px solid #ff5e2c;
            // background: #30B08F url('../../../images/student/noteLavel.png') no-repeat 0 0;
          }
        }
        .form-content {
            margin: 0 8px;
        }
        .item {
          margin-bottom: 20px;
        }
        .back {
          margin-top: 20px;
        }
        .footer {
          //float: right;
          text-align: center;
          margin-top: 40px;
        }
        .title-way {
          padding-right: 15px;
        }
        .control {
          text-align: right;
        }
      }
    }
  }
}
</style>